package org.mygui.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.mygui.bean.DBInfo;

import com.alibaba.fastjson.JSON;

public class FileUtils {

	static String fileName = "dbinfo.txt";
	public static void writeFile(String ip,int port,String dbName){
		if(null!=ip&&0!=port&&null!=dbName){
			DBInfo dbInfo = new DBInfo(ip,port,dbName);
			List<DBInfo> list = getDBList();
			if(null==list||list.size()==0){
				write(ip,port,dbName);
			}else{
				int i = 0;
				for(DBInfo db:list){
					if(dbInfo==db){
						i++;
					}
				}
				if(i==0){
					write(ip,port,dbName);
				}
			}
		}
	}
	public static void write(String ip,int port,String dbName){
		if(null!=ip&&0!=port&&null!=dbName){
			DBInfo dbInfo = new DBInfo(ip,port,dbName);
			writeInFile(JSON.toJSONString(dbInfo));
		}
	}
	public static void writeInFile(String data){
		File file =new File(fileName);
		try {
		    if(!file.exists()){
				file.createNewFile();
		    }
		    FileWriter fileWritter = new FileWriter(file.getName(),true);
	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
	        bufferWritter.write(data);
	        bufferWritter.newLine();
	        bufferWritter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static List<String> read(){
		List<String> list = new ArrayList<String>();
		try{
			File file =new File(fileName);
		    if(!file.exists()){
				file.createNewFile();
		    }
			//BufferedReader是可以按行读取文件  
	        FileInputStream inputStream = new FileInputStream(fileName);  
	        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));  
	        String str = null;
	        while((str = bufferedReader.readLine()) != null){
	        	System.out.println(str);
	            list.add(str);
	        }
		}catch(Exception e){
			e.printStackTrace();
		}
        return list;
	}
	public static List<DBInfo> getDBList(){
		List<DBInfo> list = new ArrayList<DBInfo>();
		List<String> list1 = read();
		if(null!=list1&&list1.size()>0){
			for(String s:list1){
				if(null!=s){
					list.add(JSON.parseObject(s,DBInfo.class));
				}
			}
		}
		return list;
	}
}
